package com.hue.gulimail.gulimailauth.web;

import com.alibaba.fastjson.TypeReference;
import com.hue.common.utils.HttpUtils;
import com.hue.common.utils.R;
import com.hue.common.vo.UserVo;
import com.hue.gulimail.gulimailauth.feign.MemberFeignService;
import com.hue.gulimail.gulimailauth.vo.SocialUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author: 姚凤桥
 * @Date: 2021/12/10 21:04
 * @Description: 处理社交登录的控制类
 */
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    private final String weiboLoginUrl = "https://api.weibo.com/oauth2/access_token";

    /**
     * 社交登录成功后回调页
     *
     * @param code
     * @return
     */
    @GetMapping("oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, RedirectAttributes redirectAttributes, HttpSession httpSession) {
        //使用code换取access_token
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("client_id", "3699922881");
        params.add("client_secret", "6113f5adee3612cdb6cd2636b36f2c16");
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://auth.gulimail.com/oauth2.0/weibo/success");
        params.add("code", code);

        SocialUserVo socialUserVo = HttpUtils.doPost(weiboLoginUrl, params, SocialUserVo.class);

        //验证失败,跳转到登录页面
        if (socialUserVo == null) {
            return "redirect:http://auth.gulimail.com";
        }

        //验证成功，判断用户有没有注册，如果没有就注册，有就直接登录
        R r = memberFeignService.socialLogin(socialUserVo);
        if ((Integer) r.get("code") == 0) {
            UserVo userVo = r.getData(new TypeReference<UserVo>() {
            });
            httpSession.setAttribute("user", userVo);
            return "redirect:http://gulimail.com";
        }

        redirectAttributes.addFlashAttribute("error", r.get("msg"));
        return "redirect:http://auth.gulimail.com";
    }
}
